<?php

class TestingsController extends AppController
{
	var $name = 'Testings';
	var $uses = array('Testing', 'ClientAdmin', 'Operation');
	var $helpers = array('Html', 'Form', 'Xml');
	var $po_domain = '';
	var $url_part = '';

	function beforeFilter()
	{
		parent::beforeFilter();
		$this->modelName = 'Testing';
		$this->po_domain = Inflector::underscore($this->name);
		$this->set('po_domain', $this->po_domain);
		$this->set('url_part',  $this->url_part);
		$this->set('modelName', $this->modelName);
		$this->set('PKName',    $this->{$this->modelName}->primaryKey);
		$this->po_domain = Inflector::underscore($this->name);
	}

	public function questionnaireEnd()
	{
        Auth::Access("*");

        $this->layout = 'xml/default';
        nodebug();

        $result = 'false';
        $error_code = null;
        $http_error_code = '400';
        $message = null;

		// удаляем пароль прохождения из сессии
		$this->Session->delete('applet.pass');

		$auth = isset($_REQUEST['auth']) ? $_REQUEST['auth'] : null;
		$answers = isset($_REQUEST['result']) ? $_REQUEST['result'] : "";
		if ($testing = $this->Session->read('testing')) {
		    $this->Testing->rel('Client');
            $db_testing = $this->Testing->findById($testing['Testing']['id']);
            if ($db_testing['Testing']['pass_status'] != 'IN_PROGRESS') {
                $message = __d(null, 'Test was not started normally. It was not completed successfully', true);
            } else {
    			if (isset($auth) && ($testing['Testing']['auth_link'] == $auth)) {
    			    $error_msg = '';
                    try
    				{
    					$this->Operation->paymentTest($testing['Testing']['candidate_id'], $testing['Testing']['id'], $answers);
                        $result = 'true';
    				}
    	    		catch (Exception $e)
    	    		{
    	    		    $error_code = $e->getCode();
        		    	if ($error_code == 1002)
        		    	{
        		    	    $error_code = null;
                	    	$error_msg = __d('passes', 'Insufficient balance'.(Auth::o()->is('admin') ? "_admin" : ""), true);
    					}
    					else
    					{
    	    	    		$error_msg = __d(null, 'There was an internal error.', true);
                            $http_error_code = '500';
    	    			}
        			}
        			if (! empty($error_msg)) {
                        $message = $error_msg;
        			}
                } else {
                    $message = __d($this->po_domain, 'Security rules are not obeyed. Test is not passed', true);
                }
    			$this->Session->delete('testing');
            }
		} else {
            $message = __d($this->po_domain, 'Security rules are not obeyed. Test is not passed', true);
		}
		if ($result != 'true') {
            //header('HTTP/1.1 '.$http_error_code);
		}
        $this->set('result', $result);
        $adds = isset($error_code) ? " (".__d(null, "error_code", true)." ".sprintf(__d(null, "number_with_sign", true), $error_code).")" : "";
        $this->set('message', $message.$adds);
	}

    public function questionnaireStart()
    {
        Auth::Access('*');

        $this->layout = 'xml/default';
        nodebug();
        $modelName = $this->modelName;
        $PKName    = $this->{$modelName}->primaryKey;
        $po_domain = $this->po_domain;
        $url_part  = '';
        $TestingModel = $this->{$modelName};
        if (! ($testing = $this->Session->read('testing'))) {
            $this->set('result', 'false');
            $this->set('message', __d(null, 'Test did not start properly', true));
            return false;
        }
        $testing[$modelName]['pass_status'] = 'IN_PROGRESS';
        if ($TestingModel->save($testing)) {
            $this->set('result', 'true');
        } else {
            $this->set('result', 'false');
            $this->set('message', __d($this->po_domain, 'Could not change the state of the test', true));
            return false;
        }
    }

    function completed_testings()
    {
        Auth::Access('admin | REPORTS');
	    $modelName = $this->modelName;
		$PKName    = $this->{$modelName}->primaryKey;
		$po_domain = $this->po_domain;
		$url_part  = '';

        $is_ajax = (!empty($this->params['ajax']) && ($this->params['ajax'] == 'Y'));

        $this->pageTitle = __d($po_domain, 'completed_testings_title', true);

        if ($is_ajax) {
            $this->layout = 'ajax';
        }
        $this->set('is_ajax', $is_ajax);

		if (Auth::o()->is('admin')) {
		    if (isset($this->params['client_id'])) {
    	        $this->data["client_id"] = $this->params['client_id'];
    	    } else {
                $this->error(404);
    	    }
		} else {
            $auth_data =& Auth::getUser()->data();
            $this->data["client_id"] = $auth_data["client_id"];
		}
	    if (isset($this->params['test_id'])) {
	        $this->data["test_id"] = $this->params['test_id'];
	    } else {
            $this->error(404);
	    }

	    try {

            $fields = array(
                "test_id" => null,
                "client_id" => null,
            );

			/**
			 * Считывание необходимых полей
			 */
			$fields["test_id"] = isset($this->data['test_id']) ? intval(trim($this->data['test_id'])) : null;
			$fields["client_id"] = isset($this->data['client_id']) ? intval(trim($this->data['client_id'])) : null;

            if (empty($fields["test_id"]) || empty($fields["client_id"])) {
                $this->error(404);
            }


            $Test =& $this->{$modelName}->getModel('Test'); /* @var $Test Test */
            $Test->rel();
            $test = $Test->read(null, $fields["test_id"]);
            if (empty($test[$Test->name][$Test->primaryKey])) {
				throw new ArgException();
            }

            $Client =& $this->{$modelName}->getModel('Client'); /* @var $Client Client */
            $Client->rel();
            $client = $Client->read(null, $fields["client_id"]);
            if (empty($client[$Client->name][$Client->primaryKey])) {
				throw new ArgException();
            }

            /**
             *
             */
            if (Auth::o()->is('admin')) {
                $url_part = 'client/'.$fields["client_id"].'/test/'.$fields["test_id"].'/completed_testings'.($is_ajax ? '_ajax' : '');
            } else {
                $url_part = 'test/'.$fields["test_id"].'/completed_testings'.($is_ajax ? '_ajax' : '');
            }
            $this->set('url_part', $url_part);


            /**
             *
             */
            $Candidate =& $this->{$modelName}->getModel('Candidate'); /* @var $Candidate Candidate */



    		vendor('contingencies');
    		vendor('order_html');
    		vendor('pagination_html');
    		vendor('page_of_data');

    		$contingencies = new Contingencies();
            $contingencies->model =& $this->{$modelName};
            $contingencies->expects = 'Candidate.Group | Test';

            /////////////////////////////////////////////////////////////
            $ses_war_name = __CLASS__.':'.__FUNCTION__.'_filter';
            if (!empty($this->data['Filter'])) {
                if (!empty($this->data['Filter']['submit_reset'])) {
                    unset($_SESSION[$ses_war_name]);
                    unset($this->data['Filter']);
                } elseif (!empty($this->data['Filter']['submit_apply'])) {
                	$_SESSION[$ses_war_name] = $this->data['Filter'];
                }
            }
            $filter = isset($_SESSION[$ses_war_name]) ? $_SESSION[$ses_war_name] : array();
            if (!isset($filter['searche_all'])) {
            	$filter['searche_all'] = true;
            }

            if (Auth::o()->is('admin') || Auth::o()->is('ARCHIVE')) {
        		if (!isset($filter['archived'])) {
                    $filter['archived'] = 'N';
                }
            }

            $this->data['Filter'] = $filter;
            /////////////////////////////////////////////////////////////
    		$conds = array();
    		$conds[]["`{$modelName}`.`test_id`"] = $fields["test_id"];
    		$conds[]["`{$modelName}`.`client_id`"] = $fields["client_id"];
    		$conds[]["`{$modelName}`.`pass_status`"] = 'PASSED';
    		$conds[]["not"]["`{$modelName}`.`result`"] = null;
    		$conds[]["not"]["`{$modelName}`.`result`"] = "";
    		if (!empty($filter['candidate_group_id'])) {
                $conds[]["`{$Candidate->name}`.`candidate_group_id`"] = $filter['candidate_group_id'];
    		}
    		$candidate_conds = array();
            if (!empty($filter['searche'])) {
                $searche_fields = array(
                    "`{$Candidate->name}`.`name`",
                    "`{$Candidate->name}`.`name_latin`",
                    "`{$Candidate->name}`.`surname`",
                    "`{$Candidate->name}`.`surname_latin`",
                    "`{$Candidate->name}`.`email`",
                    "`Group`.`name`",
                );
                $searche_fields_name = array(
                    "name",
                    "name_latin",
                    "surname",
                    "surname_latin",
                    "email",
                    "__group__",
                );
                $searche_params = array(
                    'entirely'  => !empty($filter['searche_entirely']),
                    'all'       => !empty($filter['searche_all']),
                    'sequence'  => !empty($filter['searche_sequence']),
                    'grouping'  => 'words', // chars
                    'words'     => false,
                );
                $candidate_conds[] = $this->{$modelName}->searcheCond($filter['searche'], $searche_fields, $searche_params);
            }
            if (Auth::o()->is('admin') || Auth::o()->is('ARCHIVE')) {
        		if (!empty($filter['archived'])) {
                    $conds[]["`{$Candidate->name}`.`archived`"] = $filter['archived'];
        		}
            } else {
                $conds[]["`{$Candidate->name}`.`archived`"] = 'N';
            }
    		////////////////////////////////////////////////////////////////////////
            if (! empty($candidate_conds)) {

                if (Auth::o()->is('admin') || Auth::o()->is('ARCHIVE')) {
            		if (!empty($filter['archived'])) {
                        $candidate_conds[]["`{$Candidate->name}`.`archived`"] = $filter['archived'];
            		}
                } else {
                    $candidate_conds[]["`{$Candidate->name}`.`archived`"] = 'N';
                }

                $candidate_conds[]["`Candidate`.`client_id`"] = $fields['client_id'];
                $candidate_list = $Candidate->generateList($candidate_conds);
                if (empty($candidate_list)) {
                    $candidate_list = array();
                }
                $conds[]["`{$modelName}`.`candidate_id`"] = array_keys($candidate_list);

            }
            $contingencies->conditions =& $conds;
    		////////////////////////////////////////////////////////////////////////

            $onclick_callback = $is_ajax ? '__ToolGUIEnv.onCandidatesBrowise' : null;
    		$this->set('onclick_callback', $onclick_callback);

    		$appearence = new OrderHTML();
            $appearence->orderFields = array(
                'surname' => "`{$Candidate->name}`.`surname`",
                'name' => "`{$Candidate->name}`.`name`",
                'created' => "`{$Candidate->name}`.`created`",
                'pass_date' => "`{$modelName}`.`pass_date`",
                'test_name' => "`Test`.`name`",
                'email' => "`{$Candidate->name}`.`email`",
                'group' => "`{$Candidate->name}`.`candidate_group_id`",
                'archived' => "`{$Candidate->name}`.`archived`",
            );
            $appearence->defaultOrder = Order::parseString('surname');
            $appearence->onclick_callback = $onclick_callback;
            $appearence->processParams();

            $pagination = new PaginationHTML();
            $pagination->defaultLimit = 5;
            $pagination->onclick_callback = $onclick_callback;
            $pagination->processParams();

            $list = new PageOfData($contingencies, $appearence, $pagination);

            if (!empty($filter['searche'])) {
                foreach ($list->rows as &$row) {
                    $row[$Candidate->name]['__group__'] = $row[$Candidate->name]['Group']['name'];
                	$this->{$modelName}->hightlightSearche($row[$Candidate->name], $filter['searche'], $searche_fields_name, $searche_params);
                    $row[$Candidate->name]['Group']['name'] = $row[$Candidate->name]['__group__'];
                    unset($row[$Candidate->name]['__group__']);
                }
            }
            $this->set('archived_list', $Candidate->getArchivedStatusesList());
            $this->set('candidate_groups_list', $this->{$modelName}->getModel('CandidateGroup')->generateList());

    		$this->set('list', $list);

	    } catch (Exception $e) {
	        exit;
	    }
    }

    function enter_result()
    {
        Auth::Access('admin | CANDIDATES');
        $modelName = $this->modelName;
        $PKName    = $this->{$modelName}->primaryKey;
        $po_domain = $this->po_domain;
        $url_part  = array('controller' => 'candidates', 'action' => 'list_of');

        /**
         * Проверка параметров из URL (Сувчествует ли така страница?).
         */
        $candidate_id = null;
        if (isset($this->params['candidate_id'])) {
            $candidate_id = $this->params['candidate_id'];
        }
        if (empty($candidate_id)) {
            $this->msgError(__d('candidates', 'absent', true), @$error_code);
            $this->redirect($url_part, null, true);
            exit();
        }
        $testing_id = null;
        if (isset($this->params['testing_id'])) {
            $testing_id = $this->params['testing_id'];
        }
        if (empty($testing_id)) {
            $this->msgError(__d('candidates', 'absent', true), @$error_code);
            $this->redirect($url_part, null, true);
            exit();
        }

        $this->{$modelName}->rel("Test");
        $conds = array();
        $conds[]["`{$modelName}`.`{$PKName}`"] = $testing_id;
        $conds[]["`{$modelName}`.`candidate_id`"] = $candidate_id;
        if (Auth::o()->is('client_admin')) {
            $auth_data = Auth::o()->data();
            $conds[]["`{$modelName}`.`client_id`"] = $auth_data['client_id'];
        }
        $conds[]["`{$modelName}`.`pass_status`"] = 'IN_PROGRESS';
        $testing = $this->{$modelName}->find($conds);
        if (empty($testing[$modelName][$PKName])) {
            $this->msgError(__d('candidates', 'Wrong tool', true), @$error_code);
            $this->redirect($url_part, null, true);
            exit();
        }
        /**
         * Конец проверки параметров.
         */

        $url_part = array('controller' => 'candidates', 'action' => 'tools', 'id' => $candidate_id);
        $this->set("url_part", $url_part);

        $this->pageTitle = strip_tags(__d('testings', 'enter_result_title', true));

		////// MENU ///////////////////////

	    $this->MainMenu->setActive($this->MainMenu->findItem(Router::url($url_part)));

		///////////////////////////////////

        if (! empty($this->data)) {
            $toolParams = $this->{$modelName}->getModel("Test")->getParamsFor($testing['Test']['name']);
            $error_msg = "";
            $success_msg = __d("candidates", 'Answers have been saved', true);
            if (! isset($this->data[$modelName]['result'])) {
                $this->data[$modelName]['result'] = "";
            }
            $raw_answers = $this->data[$modelName]['result'];
            $Test =& $this->{$modelName}->getModel("Test"); /* @var $Test Test */
            $notFilling = $Test->normalizeAnswersFor($testing["Test"]["name"], $this->data[$modelName]['result']);

            if (($testing["Test"]["type"] == "QUEST") && count($notFilling)) {
                $error_msg = __d('validation', 'answers_validation_error', null);
            }

            $this->data = $testing;
            $this->data[$modelName]['result'] = $Test->packAnswersToStringFor($testing["Test"]["name"], $raw_answers);

            if (empty($error_msg)) {
                try
				{
					$this->Operation->enterResultTest($testing['Testing']['candidate_id'], $testing['Testing']['id'], $this->data[$modelName]['result']);
				}
				catch (ArgException $e)
				{
	    		    $error_code = $e->getCode();
					$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
	    		}
	    		catch (Exception $e)
	    		{
	    		    $error_code = $e->getCode();
    		    	if ($error_code == 1002)
    		    	{
    		    	    $error_code = null;
            	    	$error_msg = __d('passes', 'Insufficient balance'.(Auth::o()->is('admin') ? "_admin" : ""), true);
					}
					else
					{
	    	    		$error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
	    			}
    			}
            	if (empty($error_msg)) {
                    $this->msgNotice($success_msg);
                    // переходим на страницу назначения инструментов
                    $this->redirect($url_part, null, true);
                    exit;
            	} else {
                    $this->data[$modelName]['result'] = $raw_answers;
                    $this->msgError($error_msg, @$error_code);
            	}
            } else {
                $this->data[$modelName]['result'] = $raw_answers;
                $this->msgError($error_msg, @$error_code);
            }
        } else {
            $this->data = $testing;
        }
    }
}

?>